package com.team2.cyber_eye.ActivityHelpers;

import java.util.Comparator;

import com.team2.shared.Product;

public class ProductSortComparator implements Comparator<Product> {
	public String Sort;
	
    @Override
    public int compare(Product p1, Product p2) {
    	String sortType = Sort;
    	
    	if (sortType == null)
    		sortType = "Price Low-High";
    	
    	if (p1==null && p2==null) return 0;
    	else if (p1==null) return -1;
    	else if (p2==null) return 1;
    	
    	if (sortType.equalsIgnoreCase("Alphabetical A-Z"))
    		return safeCompare(p1.getTitle(), p2.getTitle());
    	else if (sortType.equalsIgnoreCase("Alphabetical Z-A"))
    		return safeCompare(p2.getTitle(), p1.getTitle());
    	    	
    	else if (sortType.equalsIgnoreCase("Image Similarity Best-Worst"))
    		return safeCompare(p1.getSimilarity(), p2.getSimilarity());
    	else if (sortType.equalsIgnoreCase("Image Similarity Worst-Best"))
    		return safeCompare(p2.getSimilarity(), p1.getSimilarity());


        else if (sortType.equalsIgnoreCase("Price High-Low"))
        {
            double price1 = StringExtractAnyNumber(p1.getPrice());
            double price2 = StringExtractAnyNumber(p2.getPrice());
            return safeCompare(price2, price1);
        }
        else if (true || sortType.equalsIgnoreCase("Price Low-High"))// keeping extra case just to make it clear what this does
        {
            double price1 = StringExtractAnyNumber(p1.getPrice());
            double price2 = StringExtractAnyNumber(p2.getPrice());
            return safeCompare(price1, price2);
        }
    	
    	return 0;
    }
    
    int safeCompare(String a, String b)
    {
    	if (a==null && b==null) return 0;
    	else if (a==null) return -1;
    	else if (b==null) return 1;
    	
    	return a.compareTo(b);
    }
    
    int safeCompare(double a, double b)
    {
    	return Double.compare(a, b);
    }

    double StringExtractAnyNumber(String str)
    {
        if (str == null) return 0;
       
        final String NUMERICS = "01234567890.";
        double number = 0;
        String numberString = "0";
        for (int itr = 0; itr < str.length(); itr++)
        {
            char c = str.charAt(itr);
            if (NUMERICS.indexOf((int)c) >= 0)
            	numberString += c;
        }
        try {number = Double.valueOf(numberString);}catch (Exception ex){};
        return number;
    }
}
